﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml.Linq;

namespace LinqToLfsWorld.Queries
{
	/// <summary>
	/// Queries host status information from LfsWorld.
	/// </summary>
	public class HostStatusQuery : LfsWorldQuery<HostStatus>
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="HostStatusQuery"/> class.
		/// </summary>
		/// <param name="context">The context.</param>
		public HostStatusQuery(LfsWorldContext context)
			: base(context)
		{
		}

		/// <summary>
		/// Gets the URL used to query LfsWorld.
		/// </summary>
		/// <returns></returns>
		protected override string GetUrl()
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("http://www.lfsworld.net/hoststatus/?");
			sb.AppendFormat("h={0}", HttpUtility.UrlEncode(ExpressionValues["HostName"].Value.ToString()));

			// Optional parameters
			if (ExpressionValues.ContainsKey("ContentOnly") && ((bool)ExpressionValues["ContentOnly"].Value) == true)
				sb.AppendFormat("&onlycontent");

			if (ExpressionValues.ContainsKey("HostNameColour") &&
				((HostStatusColour)ExpressionValues["HostNameColour"].Value != HostStatusColour.Default))
				sb.AppendFormat("&c={0:d}", ExpressionValues["HostNameColour"].Value);

			if (ExpressionValues.ContainsKey("UseLfsJoinLink") &&
				((bool)ExpressionValues["UseLfsJoinLink"].Value) == true)
				sb.AppendFormat("&hostlink");

			return sb.ToString();
		}

		/// <summary>
		/// Gets the entities given LfsWorld response XML
		/// </summary>
		/// <param name="responseData">The response data.</param>
		/// <returns>A collection of Host entities</returns>
		protected override IEnumerable<HostStatus> ProcessResponse(string responseData)
		{
			// This is a bit special case, since we're only ever going to return one document;
			HostStatus status = new HostStatus();

			status.HostName = (string)ExpressionValues["HostName"].Value;
			status.Markup = responseData;			
			status.UseLfsJoinLink = ExpressionValues.ContainsKey("UseLfsJoinLink") 
						? (bool)ExpressionValues["UseLfsJoinLink"].Value 
						: false;

			status.ContentOnly = ExpressionValues.ContainsKey("ContentOnly") 
						? (bool)ExpressionValues["ContentOnly"].Value 
						: false;

			status.HostNameColour = ExpressionValues.ContainsKey("HostNameColour") 
						? (HostStatusColour)ExpressionValues["HostNameColour"].Value 
						: HostStatusColour.Default;

			return new HostStatus[] { status };
		}
	}
}
